package com.carnation._concurrent_collection;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * LinkedBlockQueue
 * </p>
 *
 * @author: Sunny
 * @date: 2021/2/2
 * @version: v1.0.0
 */
@ConditionalOnProperty
public class LinkedBlockingQueueTest {

    public static void main(String[] args) {
        BlockingQueue queue = new LinkedBlockingQueue(1);
        Thread producer = new Thread(() -> {
            try {
                queue.put("1");
                System.out.println(Thread.currentThread().getName() + " : 1");
                TimeUnit.SECONDS.sleep(1);
                queue.put("2");
                System.out.println(Thread.currentThread().getName() + " : 2");
                TimeUnit.SECONDS.sleep(1);
                queue.put("3");
                System.out.println(Thread.currentThread().getName() + " : 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "producer");
        Thread consumer = new Thread(() -> {
            try {
                // 若注释掉以下三行：则会阻塞到put("2")处，因为队列满了
                System.out.println(Thread.currentThread().getName() + " : " + queue.take());
                System.out.println(Thread.currentThread().getName() + " : " + queue.take());
                System.out.println(Thread.currentThread().getName() + " : " + queue.take());
                // 若开放注释：队列为空，则阻塞
                //System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consumer");
        producer.start();
        consumer.start();
    }

}
